package com.kaiwukj.android.ufamily.utils;

import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.kaiwukj.android.ufamily.mvp.http.api.Api;
import com.kaiwukj.android.ufamily.mvp.http.entity.bean.SubImageBean;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.FileBean;
import com.kaiwukj.android.ufamily.mvp.listener.OnSubDataUpdateListener;
import com.kaiwukj.android.ufamily.mvp.listener.OnUploadImageListener;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import timber.log.Timber;

public class QiNiuUtil {

    private OnSubDataUpdateListener listener;
    private OnUploadImageListener mListener;
    private UpdateAudioListener updateAudioListener;
    private UpdateVideoListener updateVideoListener;

    private static QiNiuUtil instance;

    public static QiNiuUtil getInstance() {
        if (instance == null) {
            instance = new QiNiuUtil();
        }
        return instance;
    }

    private QiNiuUtil() {
    }

    public QiNiuUtil(OnSubDataUpdateListener listener) {
        this.listener = listener;
    }

    public QiNiuUtil(UpdateVideoListener listener) {
        this.updateVideoListener = listener;
    }

    private List<SubImageBean> urls = new ArrayList<>();
    private List<String> filePaths = new ArrayList<>();
    private int i = 0;
    private int size = 0;

    public void uploadImages(List<FileBean> files, String token) {
    }

    public void uploadImage(String filePath, String fileName, String token, OnUploadImageListener listener) {
        this.mListener = listener;
        uploadImage(filePath, fileName, token);
    }

    public void uploadImage(List<String> filePaths, String token, OnSubDataUpdateListener listener) {
        this.listener = listener;
        size = filePaths.size();
        i = 0;
        urls = new ArrayList<>();
        for (String path : filePaths) {
            uploadImage(path, "", token);
        }
        //uploadImage(filePath, fileName, token);
    }

    @Deprecated
    public void uploadImagesToQiniu(List<String> filePaths, String token, @Nullable boolean boolFace) {
        this.filePaths = filePaths;
        uploadImage(filePaths.get(0), token, boolFace);
    }

    @Deprecated
    public void uploadImagesToQiniu(List<String> filePaths, String token) {
        this.filePaths = filePaths;
        uploadImage(filePaths.get(0), token, false);
    }

    @Deprecated
    public void uploadImageToQiniu(String filePath, String token) {
        uploadImage(filePath, token, false);
    }

    private Configuration getConfig() {
        return new Configuration.Builder()
                .connectTimeout(10)           // 链接超时。默认10秒
                //.useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                // .recorder(recorder)           // recorder分片上传时，已上传片记录器。默认null
                // .recorder(recorder, keyGen)   // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Api.zone)        // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
                .build();
    }

    private synchronized void uploadImg(final String filePath, String fileName, final String token) {
        UploadManager uploadManager = new UploadManager(getConfig(), 3);
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //String fileName = "icon_" + sdf.format(new Date()) + ".jpg";

        if (TextUtils.isEmpty(fileName)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            fileName = "img_" + sdf.format(new Date()) + ".jpg";
        }

        uploadManager.put(filePath, fileName, token, (key, info, response) -> {
            if (info.isOK()) {
                if (mListener != null) {
                    SubImageBean imageBean = new SubImageBean();
                    imageBean.setType("image");
                    imageBean.setImgUrl(key);
                }

            } else {
                if (mListener != null) {
                    //listener.onError(info.statusCode, info.error);
                }
            }
        }, new UploadOptions(null, null, false, (key, percent) -> {

        }, null));
    }

    private synchronized void uploadImage(final String filePath, String fileName, final String token) {
        UploadManager uploadManager = new UploadManager(getConfig(), 3);
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //String fileName = "icon_" + sdf.format(new Date()) + ".jpg";

        if (TextUtils.isEmpty(fileName)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            fileName = "img_" + sdf.format(new Date()) + ".jpg";
        }

        uploadManager.put(filePath, fileName, token, (key, info, response) -> {
            if (info.isOK()) {
                if (mListener != null) {
                    SubImageBean imageBean = new SubImageBean();
                    imageBean.setType("image");
                    imageBean.setImgUrl(key);
                    mListener.onSuccess(imageBean);
                }
            } else {
                if (mListener != null) {
                    mListener.onError(info.statusCode, info.error);
                }
            }
        }, new UploadOptions(null, null, false, (key, percent) -> {

        }, null));
    }

    /**
     * 上传图片到七牛
     *
     * @param filePath 要上传的图片路径
     * @param token    在七牛官网上注册的token
     */
    @Deprecated
    private synchronized void uploadImage(final String filePath, final String token, @Nullable boolean boolFace) {
        UploadManager uploadManager = new UploadManager(new Configuration.Builder().zone(Api.zone).build());
        String key = "";
        if (!boolFace) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            key = "icon_" + sdf.format(new Date()) + ".jpg";
            // 设置图片名字
        } else {
            key = SPUtils.getInstance().getString("EXTRA_FACE_NAME", "");
        }

        uploadManager.put(filePath, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                // info.error中包含了错误信息，可打印调试
                // 上传成功后将key值上传到自己的服务器
                Timber.e("上传失败信息%s", info.error);
                String url;
                if (boolFace) {
                    url = key;
                } else {
                    url = Api.QI_IMG + key;
                }
//                LogUtils.i("url ---> " + url);
                SubImageBean subImageBean = new SubImageBean();
                subImageBean.setType(i + 1 + "");
                subImageBean.setImgUrl(url);
                urls.add(subImageBean);
                i++;
                if (filePaths.size() > urls.size()) {
                    uploadImageToQiniu(filePaths.get(i), token);
                }
                if (filePaths.size() == urls.size()) {
                    listener.onUpdateUrls(urls);
                }
                //单张图片上传，头像场景
                if (filePaths.size() == 0 && urls.size() != 0) {
                    listener.onUpdateUrls(urls);
                }
            }
        }, new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    public void progress(String key, double percent) {
//                        Log.i("qiniu", key + ": " + percent);
//                        LogUtils.i(key + ": " + percent);
                    }
                }, null));
    }

    public void uploadeVideo(final String filePath, final String token, UpdateVideoListener listener) {
        this.updateVideoListener = listener;
        uploadeVideo(filePath, token);
    }

    /**
     * 上传视频到七牛
     *
     * @param filePath 要上传的视频路径
     * @param token    在七牛官网上注册的token
     */
    public void uploadeVideo(final String filePath, final String token) {
        UploadManager uploadManager = new UploadManager(new Configuration.Builder().zone(Api.zone).build());
        // 设置图片名字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String key = "video_" + sdf.format(new Date()) + ".mp4";

        uploadManager.put(filePath, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                String url = Api.QI_IMG + key;
                updateVideoListener.updateVideo(url);
            }
        }, new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    public void progress(String key, double percent) {
                    }
                }, null));
    }

    /**
     * 上传录音到七牛
     *
     * @param filePath 要上传的录音路径
     * @param token    在七牛官网上注册的token
     */
    public void uploadeAudio(final String filePath, final String token) {
        UploadManager uploadManager = new UploadManager(new Configuration.Builder().zone(Api.zone).build());
        // 设置图片名字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String key = "audio_" + sdf.format(new Date()) + ".amr";

        uploadManager.put(filePath, key, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                String url = Api.QI_IMG + key;
                updateAudioListener.updateAudio(url);
            }
        }, new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    public void progress(String key, double percent) {
                    }
                }, null));
    }

    public interface UpdateVideoListener {
        void updateVideo(String url);
    }

    public interface UpdateAudioListener {
        void updateAudio(String url);
    }

    public void setUpdateAudioListener(UpdateAudioListener updateAudioListener) {
        this.updateAudioListener = updateAudioListener;
    }

    public void setUpdateVideoListener(UpdateVideoListener updateVideoListener) {
        this.updateVideoListener = updateVideoListener;
    }
}
